import java.io.*;
import java.lang.reflect.Method;


/**
 * @author ：xuanlong
 * @date ：Created in 2021/8/4 9:20 PM
 * @description：TODO
 * @modified By：
 * @version: 0.0.1
 */
public class XlassLoader extends ClassLoader{
    public static void main(String[] args) throws Exception{
        Class c =  new XlassLoader().findClass("Hello");
        Method method = c.getMethod("hello");
        method.invoke(c.newInstance());

    }

    @Override
    protected Class<?> findClass(String name) {

        File file = new File("src/main/resources/Hello.xlass");
        byte[] bytes = null;
        try {
           bytes = decode(toByteArray(file));
        }catch (IOException ex){
            ex.printStackTrace();
        }
        return defineClass(name,bytes,0,bytes.length);

    }
    public static byte[] toByteArray(File file) throws IOException {
        File f = file;
        if (!f.exists()) {
            throw new FileNotFoundException("file not exists");
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }

    public byte[] decode(byte[] bytes){
        byte[] resultBytes = bytes;
        for(int i = 0; i<bytes.length;i++){
            resultBytes[i] = (byte) ((byte)255- bytes[i]);
        }
        return  resultBytes;
    }
}
